#!/bin/bash
# Spring Boot 生产环境启动脚本（强制优雅停机版）
# 使用方式：./start.sh [start|stop|restart|status]

# 应用配置（需修改）
APP_NAME="ldms"          # 应用名称
JAR_FILE="./app.jar"     # JAR包路径
LOG_DIR="./log/${APP_NAME}"       # 日志目录
PID_FILE="${LOG_DIR}/${APP_NAME}.pid" # PID文件
WAIT_TIMEOUT=60                      # 等待优雅停机的超时时间（秒）
JAVA_OPTS_EXT="-Djasypt.encryptor.password=ABCDEFGH12345678"
# JVM 生产环境推荐配置
JAVA_OPTS_EXT=" ${JAVA_OPTS_EXT} -Dthread-pools.configs.cnaps-pool.core-pool-size=100 -Dthread-pools.configs.cnaps-pool.max-pool-size=200 -Dthread-pools.configs.cnaps-pool.queue-capacity=500"
JAVA_OPTS="-server -Xms4g -Xmx4g -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:InitiatingHeapOccupancyPercent=35 -XX:MetaspaceSize=256M -XX:+DisableExplicitGC -Xloggc:./log/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Dspring.profiles.active=prod  ${JAVA_OPTS_EXT} "

# 创建日志目录
mkdir -p ${LOG_DIR} || { echo "ERROR: Cannot create log directory"; exit 1; }

# 启动函数
start() {
  if [ -f ${PID_FILE} ]; then
    PID=$(cat ${PID_FILE})
    if ps -p ${PID} > /dev/null; then
      echo "WARN: ${APP_NAME} is already running (PID: ${PID})"
      exit 1
    fi
  fi

  echo "Starting ${APP_NAME}..."
  nohup java ${JAVA_OPTS} \
    -Dlogging.file.path=${LOG_DIR} \
    -jar ${JAR_FILE} > ${LOG_DIR}/console.log 2>&1 &

  echo $! > ${PID_FILE}
  echo "Started (PID: $!)"
}

# 优雅停止函数（核心改进点）
stop() {
  if [ ! -f ${PID_FILE} ]; then
    echo "ERROR: PID file not found: ${PID_FILE}"
    exit 1
  fi

  PID=$(cat ${PID_FILE})
  if ! ps -p ${PID} > /dev/null; then
    echo "WARN: Process not found (PID: ${PID}), deleting PID file"
    rm -f ${PID_FILE}
    exit 1
  fi

  echo "Stopping ${APP_NAME} (PID: ${PID}) gracefully..."
  kill -15 ${PID}  # 发送SIGTERM信号

  # 等待应用自行关闭
  local count=0
  while [ ${count} -lt ${WAIT_TIMEOUT} ]; do
    if ! ps -p ${PID} > /dev/null; then
      rm -f ${PID_FILE}
      echo "Stopped gracefully"
      return 0
    fi
    sleep 1
    ((count++))
  done

  # 超时后强制终止
  echo "WARN: Force stopping after ${WAIT_TIMEOUT} seconds..."
  kill -9 ${PID} 2>/dev/null
  rm -f ${PID_FILE}
  echo "Stopped by force"
}

# 状态检查
status() {
  if [ -f ${PID_FILE} ]; then
    PID=$(cat ${PID_FILE})
    if ps -p ${PID} > /dev/null; then
      echo "${APP_NAME} is running (PID: ${PID})"
      return 0
    else
      echo "${APP_NAME} is not running (stale PID file)"
      return 1
    fi
  else
    echo "${APP_NAME} is not running"
    return 1
  fi
}

# 主逻辑
case "$1" in
  start)  start ;;
  stop)   stop ;;
  restart) stop && sleep 2 && start ;;
  status) status ;;
  *)      echo "Usage: $0 {start|stop|restart|status}"; exit 1 ;;
esac

exit $?
